package com.quick.springbootquicky.service.impl;

import com.quick.springbootquicky.mapper.CategoryMapper;
import com.quick.springbootquicky.pojo.Article;
import com.quick.springbootquicky.pojo.Category;
import com.quick.springbootquicky.service.ArticleService;
import com.quick.springbootquicky.service.CategoryService;
import com.quick.springbootquicky.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ArticleService articleService;

    /**
     * 新增文章
     * @param category
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Category category) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        category.setCreateUser(userId);
        categoryMapper.add(category);
    }

    /**
     * 查询文章列表
     * @return
     */
    @Override
    public List<Category> list() {
        // 获取当前登入者的Id
        //从当前线程中获取,在拦截器中清除
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        return categoryMapper.list(userId);
    }

    /**
     * 根据文章id查询数据
     * @param id
     * @return
     */
    @Override
    public Category findById(Integer id) {
        return categoryMapper.findById(id);
    }

    /**
     * 根据文章id更新文章
     * @param category
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Category category) {
        category.setUpdateTime(new Date());
         categoryMapper.update(category);
    }

    /**
     * 删除文章
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        List<Article> list = articleService.findByCategoryId(id);
        if(!list.isEmpty() && list.size() >0){
            throw new RuntimeException("数据被引用,不允许删除");
        }
        categoryMapper.delete(id);
    }
}
